package cn.wolfcode.user.servlet;

import cn.wolfcode.entity.UserMer;
import cn.wolfcode.user.entity.User;
import cn.wolfcode.user.service.UserService;
import cn.wolfcode.user.service.impl.UserServiceImpl;
import cn.wolfcode.util.IsNotNullUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 李新雨的项目86176
 * @version 1.0
 * @date 2024-10-28 20:57
 */
@WebServlet("/user")
public class UserServlet extends HttpServlet {
    private final UserService userService = new UserServiceImpl();



    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String rememberMe = req.getParameter("rememberMe");
        String userIn = req.getParameter("randomCode");
        String randomCodeInSession = req.getSession().getAttribute("RANDOMCODE_IN_SESSION").toString();
        if(!(IsNotNullUtils.isNotNull(userIn)&&IsNotNullUtils.isNotNull(randomCodeInSession)&&userIn.equalsIgnoreCase(randomCodeInSession))){
            req.setAttribute("codeMsg","验证码错误");
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
            return;
        }

        //// TODO: 2024/11/6  
//        System.out.println(randomCode+"-------------"+rememberMe);
//        User user = null;
        //// TODO: 2024/10/30
        try {
           User user = userService.login(username, password);
            /**
             *cookie
             */
            boolean remMe = Boolean.parseBoolean(rememberMe);
            Cookie cookie = new Cookie("username", username);
            if(remMe){
                cookie.setMaxAge(UserMer.COOKIE_TIME.getOneWeek());
            }
            resp.addCookie(cookie);


            //// TODO: 2024/11/6  验证码问题
           //// TODO: 2024/10/30 共享数据
           req.getSession().setAttribute("USER_IN_SESSION",user);
            //
            resp.sendRedirect("/book");
        } catch (Exception e) {
            e.printStackTrace();
            req.setAttribute("msg","用户名或密码错误");
//            resp.sendRedirect("/login.jsp");
            // TODO: 2024/10/30 为什么
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
        }
    }
}